﻿using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Windows;

namespace start
{
    static class Startup
    {

        public static string LastestVersion;
        public static string CurrentVersion;
        public static string UpgradeFileList;
        private static string serverURL = ConfigurationManager.AppSettings["serverURL"];

        [STAThread]
        static void Main(string[] args)
        {
            try
            {
                Download("checklist.txt");
                Read("checklist.txt");

                FileVersionInfo fvi = FileVersionInfo.GetVersionInfo("wms.exe");
                CurrentVersion = fvi.FileVersion;

                float lastest = ToNumVersion(LastestVersion);
                float current = ToNumVersion(CurrentVersion);

                if (lastest > current)
                {
                    App app = new App();
                    Upgrade win = new Upgrade();
                    win.Closed += Win_Closed;
                    app.Run(win);
                }
                else
                {
                    Process.Start("wms.exe");
                }
            }
            catch(Exception)
            {
                Process.Start("wms.exe");
            }
        }

        private static void Win_Closed(object sender, EventArgs e)
        {
            Upgrade win = sender as Upgrade;
            if(win.Success == true)
            {
                Process.Start("wms.exe");
            }
        }

        private static float ToNumVersion(string version)
        {
            string[] array = version.Split('.');
            return float.Parse(array[0] + "." + array[1]);
        }

        public static void Read(string path)
        {
            StringBuilder sb = new StringBuilder();
            StreamReader sr = new StreamReader(path, Encoding.Default);
            string line;
            int i = 0;
            while ((line = sr.ReadLine()) != null)
            {
                if(i == 0)
                {
                    LastestVersion = line;
                }
                else
                {
                    sb.AppendLine(line);
                }
                i++;
            }
            UpgradeFileList = sb.ToString();
        }

        public static void Download(string name)
        {
            WebClient client = new WebClient();
            client.DownloadFile(serverURL + name, name); 
        }
    }
}
